//
//  AttrDataSearchViewController.m
//  dataGathering
//
//  Created by apple on 14/12/8.
//  Copyright (c) 2014年 shuili. All rights reserved.
//

#import "AttrDataSearchViewController.h"
#import "AFViewShaker.h"
#import "IMQuickSearch.h"
#import "seachResultViewController.h"
#import "SpatialSearchIndicatorViewController.h"
#import "MapMainView.h"

@interface AttrDataSearchViewController ()
@property (weak, nonatomic) IBOutlet UIButton *attrSearchTabButton;
@property (weak, nonatomic) IBOutlet UIButton *spatiailSearchTabButton;

@property (weak, nonatomic) IBOutlet UITextField *searchTextField;
@property (weak, nonatomic) IBOutlet UIScrollView *contentScrollView;

@property (weak, nonatomic) IBOutlet UIImageView *searchIndicatorImageView;

@property (nonatomic, retain)NSString *searchText;

@property (nonatomic, retain) IMQuickSearch *QuickSearch;

@property(nonatomic, assign)NSInteger selectedIndex;

@property(nonatomic, retain)LocalFeatureModel *featureModel;
@end

@implementation AttrDataSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initScrollView];
    _featureModel = [[currentWorkSetManager sharedInstance] getLocalFeatureModel];
    
    [_attrSearchTabButton setBackgroundImage:[UIImage imageNamed:@"u149_selected.png"] forState:UIControlStateHighlighted];
    [_attrSearchTabButton setBackgroundImage:[UIImage imageNamed:@"u149_selected.png"] forState:UIControlStateSelected];
    [_attrSearchTabButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
    [_spatiailSearchTabButton setBackgroundImage:[UIImage imageNamed:@"u149_selected.png"] forState:UIControlStateHighlighted];
    [_spatiailSearchTabButton setBackgroundImage:[UIImage imageNamed:@"u149_selected.png"] forState:UIControlStateSelected];
    [_spatiailSearchTabButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
    [self setAttrSearchTabButtonSelected:YES];
    
    _searchTextField.delegate = self;
    
    ((UITableViewController*)[[self childViewControllers] objectAtIndex:0]).tableView.delegate = self;
    ((UITableViewController*)[[self childViewControllers] objectAtIndex:0]).tableView.dataSource = self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toSpatialSearchIndicatorView:) name:@"toSpatialSearchIndicatorView" object:nil];
    
}

-(void)toSpatialSearchIndicatorView: (NSNotification*)noti
{
    [self performSegueWithIdentifier:@"toSpatialSearchIndicatorView" sender:[noti object]];
}

- (void)initScrollView
{
    //_contentScrollView.pagingEnabled = YES;
    //_contentScrollView.clipsToBounds = NO;
    
    //_contentScrollView.scrollsToTop = NO;
    _contentScrollView.contentSize = CGSizeMake(482*2, 600);
    _contentScrollView.delegate = self;
    [_contentScrollView setDirectionalLockEnabled:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(scrollView.contentOffset.x >= scrollView.contentSize.width/2.0){
        [_spatiailSearchTabButton setSelected:YES];
        [_attrSearchTabButton setSelected:NO];
    } else {
        [_spatiailSearchTabButton setSelected:NO];
        [_attrSearchTabButton setSelected:YES];
    }
}

- (void)setAttrSearchTabButtonSelected: (BOOL)selected
{
    [_attrSearchTabButton setSelected:selected];
    [_spatiailSearchTabButton setSelected:!selected];
    
    [_contentScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (void)setSpatialTabButtonSelected: (BOOL)selected
{
    [_spatiailSearchTabButton setSelected:selected];
    [_attrSearchTabButton setSelected:!selected];
    
    [_contentScrollView setContentOffset:CGPointMake(_contentScrollView.frame.size.width+6 , 0) animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if([segue identifier] && [[segue identifier] compare:@"attrToSearchResult"] == NSOrderedSame){
        workSet *currentWorkset = [[currentWorkSetManager sharedInstance] getCurrentWorkSet];
        [self.QuickSearch removeAllFilters];
        
        if(_selectedIndex == 100){
            IMQuickSearchFilter *searchTypeFilter = [IMQuickSearchFilter filterWithSearchArray:[currentWorkset collectedDataList] keys:@[@"name", @"idNumber"]];
            
            
            self.QuickSearch = [[IMQuickSearch alloc] initWithFilters:@[searchTypeFilter]];
            NSArray *filteredResults = [self.QuickSearch filteredObjectsWithValue:_searchText];
            NSLog(@"found data count is %lu", (unsigned long)[filteredResults count]);
            
            ((seachResultViewController*)[segue destinationViewController]).searchResultList = filteredResults;
        } else if(_selectedIndex != 20000){
            
            
            IMQuickSearchFilter *searchTypeFilter = [IMQuickSearchFilter filterWithSearchArray:[currentWorkset collectedDataList] keys:@[@"mainType"]];
            
            self.QuickSearch = [[IMQuickSearch alloc] initWithFilters:@[searchTypeFilter]];
            NSArray *filteredResults = [self.QuickSearch filteredObjectsWithValue:[(LocalGroupModel*)[[_featureModel groups] objectAtIndex:_selectedIndex] name]];
            NSLog(@"found data count is %lu", (unsigned long)[filteredResults count]);
            
            ((seachResultViewController*)[segue destinationViewController]).searchResultList = filteredResults;
        } else if(_selectedIndex == 20000){
            ((seachResultViewController*)[segue destinationViewController]).searchResultList = (NSArray*)sender;
        }
    } else if([segue identifier] && [[segue identifier] compare:@"toSpatialSearchIndicatorView"] == NSOrderedSame){
        
        ((SpatialSearchIndicatorViewController*)[segue destinationViewController]).searchType = [(NSIndexPath*)sender row];
    }
}

- (IBAction)attrSearchTabButtonClicked:(id)sender {
    [self setAttrSearchTabButtonSelected:YES];
}
- (IBAction)spatialTabButtonClicked:(id)sender {
    [self setSpatialTabButtonSelected:YES];
}


#pragma UITextFiledDelegate Methods
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    /* Set a large value to _selectedIndex to indicate it's in INPUT_STRING_SEARCH mode */
    _selectedIndex = 100;
    if([[textField text] compare:@""] == NSOrderedSame){
        AFViewShaker *shaker = [[AFViewShaker alloc] initWithViewsArray:[[NSArray alloc] initWithObjects:textField,_searchIndicatorImageView, nil]];
        [shaker shake];
        return NO;
    } else {
        _searchText = [textField text];
        [self performSegueWithIdentifier:@"attrToSearchResult" sender:nil];
#pragma warnig test only
        for (UIView* next = [[self navigationController].parentViewController.view superview]; next; next = next.superview) {
            UIResponder* nextResponder = [next nextResponder];
            if ([nextResponder isKindOfClass:[UIViewController class]]) {
                [((MapMainView*)nextResponder) queryDataFromFeatureLayers:_searchText];
            }
        }
        return YES;
    }
}

#pragma UITableView Delegate Methods
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    _selectedIndex = [indexPath row];
    [self performSegueWithIdentifier:@"attrToSearchResult" sender:nil];
}

-(void)showSpatialSearchedResult:(NSArray*)resultArray
{
    _selectedIndex = 20000;
    [self performSegueWithIdentifier:@"attrToSearchResult" sender:resultArray];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[_featureModel groups] count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, 288, 48)];
    
    NSUInteger row = [indexPath row];
    
    LocalGroupModel *group = [[_featureModel groups] objectAtIndex:row];
    
    NSString *appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [appDocumentPath stringByAppendingString:@"/LayerIcons/"];
    //NSString *iconPath = [filePath stringByAppendingString:[group icon]];
    //UIImageView *view = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:iconPath]];
    //UIImageView *view = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:@""]];
    
    //UIImageView *view = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"u141.png"]];
    //view.frame = CGRectMake(8, 6, 32 , 32);
    //view.contentMode = UIViewContentModeScaleAspectFit;
    
    UILabel *typeLabel = [[UILabel alloc] initWithFrame:CGRectMake(48, 7, 81, 19)];
    [typeLabel setFont:[UIFont systemFontOfSize:16.0]];
    [typeLabel setTextColor:[UIColor colorWithRed:77.0/255.0 green:77.0/255.0 blue:77.0/255.0 alpha:1]];
    [typeLabel setText:[group name]];
    
    //[cell.contentView addSubview:view];
    [cell.contentView addSubview:typeLabel];
    
    return cell;
}

@end
